/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aaa;

import XML.DigesterMarriesLucene;
import brut.androlib.AndrolibException;
import brut.apktool.Main;
import java.awt.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import org.apache.lucene.index.IndexReader;
import org.xml.sax.SAXException;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import javax.xml.parsers.ParserConfigurationException;
import net.sf.plist.io.PropertyListException;
import plist.PlistParser;
import zip.Unzip;

/**
 *
 * @author Bashev
 */
public class MainForm extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    
    private IndexReader ir;
    private String apkAppName;
    JProgressBar progressBar = new JProgressBar();
    JFrame f = new JFrame("Decompiling");
    
    public MainForm() throws IOException, SAXException {
        initComponents(); 
        this.setTitle("Android & Apple Analyzer");
        Image im = ImageIO.read(this.getClass().getResource("/resources/HP-Network.png"));
        this.setIconImage(im);
        //lblInfo.setVisible(false);
        //ir = DigesterMarriesLucene.parse("/Users/kurpicz/NetBeansProjects/AAA/YogaMomentLite/res/values/strings.xml"); 
        //AddressBookParser.pp("C:\\Program Files (x86)\\Java\\jdk1.7.0\\bin\\StretchExercises\\res\\values\\strings.xml");
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtApkFile = new javax.swing.JTextField();
        lblApk = new javax.swing.JLabel();
        btnChooseApkFile = new javax.swing.JButton();
        btnDecompileApkFiel = new javax.swing.JButton();
        btnTable = new javax.swing.JButton();
        btnConfig = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnExcelFIle = new javax.swing.JButton();
        btnCSVFile = new javax.swing.JButton();
        lblInfo = new javax.swing.JLabel();
        lblStatus = new javax.swing.JLabel();
        btnAdvanced = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblApk.setText("Apk/ipa/zip file:");

        btnChooseApkFile.setText("...");
        btnChooseApkFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseApkFileActionPerformed(evt);
            }
        });

        btnDecompileApkFiel.setText("Retrieve");
        btnDecompileApkFiel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDecompileApkFielActionPerformed(evt);
            }
        });

        btnTable.setText("Table");
        btnTable.setEnabled(false);
        btnTable.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTableActionPerformed(evt);
            }
        });

        btnConfig.setText("Configuration");
        btnConfig.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfigActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        jLabel1.setText("Android & Apple Analyzer");

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logo1.jpg"))); // NOI18N
        jLabel2.setText("jLabel2");
        jLabel2.setPreferredSize(new java.awt.Dimension(300, 150));

        btnExcelFIle.setText("Excel File");
        btnExcelFIle.setEnabled(false);
        btnExcelFIle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcelFIleActionPerformed(evt);
            }
        });

        btnCSVFile.setText("CSV File");
        btnCSVFile.setEnabled(false);
        btnCSVFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCSVFileActionPerformed(evt);
            }
        });

        lblInfo.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
        lblInfo.setText("Result will be displayed here");

        lblStatus.setText("Status:");

        btnAdvanced.setText("Multilingual");
        btnAdvanced.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdvancedActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblApk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtApkFile, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnChooseApkFile, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDecompileApkFiel))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnConfig)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblStatus)
                                .addGap(18, 18, 18)
                                .addComponent(lblInfo))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnTable)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnExcelFIle)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCSVFile)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnAdvanced)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblApk)
                    .addComponent(txtApkFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnChooseApkFile)
                    .addComponent(btnDecompileApkFiel))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblInfo)
                    .addComponent(lblStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnTable)
                    .addComponent(btnExcelFIle)
                    .addComponent(btnCSVFile)
                    .addComponent(btnConfig)
                    .addComponent(btnAdvanced))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnDecompileApkFielActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDecompileApkFielActionPerformed
           // PlistParser pp = new PlistParser();
              //  pp.parseP(txtApkFile.getText(), apkAppName);
            // 	    Unzip u = new Unzip();
//                u.unzipFile(txtApkFile.getText());
            if (txtApkFile.getText().endsWith(".zip") || txtApkFile.getText().endsWith(".apk") || txtApkFile.getText().endsWith(".ipa")){                                    
                try {
                try {
                    decompile();
                } catch (AndrolibException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (PropertyListException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
                lblInfo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
                lblInfo.setForeground(new java.awt.Color(0, 204, 0));
                lblInfo.setText("Processing completed!");

                btnCSVFile.setEnabled(true); 
                btnExcelFIle.setEnabled(true); 
                btnTable.setEnabled(true); 
            } else
                JOptionPane.showMessageDialog(this, "Please select correct file!", "Warning!", JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_btnDecompileApkFielActionPerformed

    public static String convertToQuotedString(String string) {
        if (string == null){
            return null;
        }
        if (string.equalsIgnoreCase("")) {
            return"";
        }        

    // append 
        return'\"' + string + '\"';
  }
    
    public void getProgressBar(){        
        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        Container content = f.getContentPane();        
        progressBar.setValue(10);
        progressBar.setStringPainted(true);
        Border border = BorderFactory.createTitledBorder("Decompiling...");
        progressBar.setBorder(border);
        content.add(progressBar);
        f.setSize(300, 100);
        f.setVisible(true);        
    }        
    
    private void progressBar() throws InterruptedException{
        getProgressBar();
        boolean loop = true;
        int count = 2;
        while (loop){                    
            progressBar.setValue(count*10);                    
            count++;
            progressBar.update(progressBar.getGraphics());
            Thread.sleep(1500);
            loop = count < 10;
        }
    } 
    
    private void decompile() throws FileNotFoundException, IOException, InterruptedException, PropertyListException, ParserConfigurationException, AndrolibException{
        ir = null;
        String savePath = "";     
        File fff = new File(txtApkFile.getText());            
        savePath = Configurator.getConfigProperty("apk_output_path")+"//" + fff.getName();
        Runnable r = new Runnable() {

                public void run() {
                    try {
                        progressBar();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
        if (txtApkFile.getText().endsWith("apk")){              
            Thread t = new Thread(r);
            t.start();            
            String params[] = {"d", "-f", txtApkFile.getText(), savePath};
            Main.main(params);
            t.join();
        } else{
            Unzip u = new Unzip();
            PlistParser pp = new PlistParser();
            java.util.List<String> files = u.unzipFile(txtApkFile.getText());
            String outputPath = Configurator.getConfigProperty("apk_output_path") + "\\";
            for (int i = 0; i < files.size(); i++) {                
                pp.parseP(outputPath + files.get(i));
            }
            File ff = new File(txtApkFile.getText());
            if (files.size() > 0){
                ir = PlistParser.write(apkAppName);
                Thread t = new Thread(r);
                t.start();
                t.join();
            }
            else {
                JOptionPane.showMessageDialog(this, "Please select correct file!", "Warning!", JOptionPane.WARNING_MESSAGE);
                return;
            }
        }        
//        getProgressBar();
//        boolean loop = true;
//        int count = 2;
//        while (loop){                    
//            progressBar.setValue(count*10);                    
//            count++;
//            progressBar.update(progressBar.getGraphics());
//            Thread.sleep(1000);
//            loop = count < 10;
//        }    
        if (txtApkFile.getText().endsWith("apk"))
            parseXML(savePath);
        f.setVisible(false);         
    }
    
    private void btnChooseApkFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseApkFileActionPerformed
        FileSystemView filesys = FileSystemView.getFileSystemView();
        String desktopPath = filesys.getHomeDirectory().getPath();
        JFileChooser fileChooserForm = new JFileChooser(desktopPath);
        fileChooserForm.setVisible(rootPaneCheckingEnabled);
        fileChooserForm.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                String filename = f.getName();
                return filename.endsWith(".apk") || filename.endsWith(".zip") || filename.endsWith(".ipa") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "*.apk, *.zip, *.ipa";
            }
        });
        int retVal =  fileChooserForm.showOpenDialog(this);
        if (retVal == JFileChooser.APPROVE_OPTION){
            txtApkFile.setText(fileChooserForm.getSelectedFile().getPath());
            apkAppName = getFileNameWithoutExtension(fileChooserForm.getSelectedFile());
            lblInfo.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
            lblInfo.setForeground(new java.awt.Color(0, 0, 0));
            lblInfo.setText("Result will be displayed here!");
            btnCSVFile.setEnabled(false); 
            btnExcelFIle.setEnabled(false); 
            btnTable.setEnabled(false);	
        }        
    }//GEN-LAST:event_btnChooseApkFileActionPerformed

    private void parseXML(String savePath){
        File f = new File(savePath+ "/res/values/strings.xml");
        try {
            ir = DigesterMarriesLucene.parse(f, apkAppName);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
    
    private void btnTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTableActionPerformed
        Results res;            
        try {
            String application = "";
            File f = new File(txtApkFile.getText());
            if (txtApkFile.getText().endsWith(".apk"))
                application = "Android - " + f.getName();
            else
                application = "Apple - " + f.getName();
            res = new Results(ir, application);            
            res.setVisible(true);            
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }//GEN-LAST:event_btnTableActionPerformed

    public static String getFileNameWithoutExtension(File f){
        int index = f.getName().lastIndexOf('.');
        if (index>0&& index <= f.getName().length() - 2 ) {
            return f.getName().substring(0, index);
        }  
        return "";        
    }
    
    private void btnConfigActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfigActionPerformed
        Configurator confi = null; 
        try {
            confi = new Configurator();
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        confi.setVisible(true);
    }//GEN-LAST:event_btnConfigActionPerformed

    public static void openFile(File f) {
        Desktop dt = Desktop.getDesktop();
        try {
            dt.open(f);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //CSV Button
    private void btnCSVFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCSVFileActionPerformed
        File f = null;
        try {
            f = new File(Configurator.getConfigProperty("xls_path")+"//"+apkAppName+".csv");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        openFile(f); 

    }//GEN-LAST:event_btnCSVFileActionPerformed
    //Excel Button
    private void btnExcelFIleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcelFIleActionPerformed
        File f = null;
        try {
            f = new File(Configurator.getConfigProperty("xls_path")+"//"+apkAppName+".xls");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        openFile(f); 
    }//GEN-LAST:event_btnExcelFIleActionPerformed

    private void btnAdvancedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdvancedActionPerformed
        Advanced adv = new Advanced();
        adv.setVisible(true);
    }//GEN-LAST:event_btnAdvancedActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new MainForm().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SAXException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdvanced;
    private javax.swing.JButton btnCSVFile;
    private javax.swing.JButton btnChooseApkFile;
    private javax.swing.JButton btnConfig;
    private javax.swing.JButton btnDecompileApkFiel;
    private javax.swing.JButton btnExcelFIle;
    private javax.swing.JButton btnTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblApk;
    private javax.swing.JLabel lblInfo;
    private javax.swing.JLabel lblStatus;
    private javax.swing.JTextField txtApkFile;
    // End of variables declaration//GEN-END:variables
}
